name: Build and deploy design.vapor.codes

on:
  push:
    branches:
    - main

jobs:
  build:
    name: Build and deploy
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v4
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: 18.12.1
        cache: npm
    - name: Build site
      run: swift run && npm install && npm run build
    - name: Configure AWS credentials
      id: cred
      uses: aws-actions/configure-aws-credentials@v4
      with:
        aws-access-key-id: ${{ secrets.DESIGN_DEPLOYER_AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.DESIGN_DEPLOYER_AWS_SECRET_ACCESS_KEY }}
        aws-region: 'eu-west-2'
    - name: Deploy to AWS Cloudformation
      id: clouddeploy
      uses: aws-actions/aws-cloudformation-github-deploy@v1
      with:
        name: vapor-design-stack
        template: stack.yml
        no-fail-on-empty-changeset: "1"
        parameter-overrides: >-
          DomainName=design.vapor.codes,
          S3BucketName=vapor-design-site,
          AcmCertificateArn=${{ secrets.CERTIFICATE_ARN }}
      if: steps.cred.outcome == 'success'
    - name: Deploy to S3
      id: s3deploy
      run: >
        aws s3 sync
        ./Output
        s3://vapor-design-site/
        --acl public-read --follow-symlinks --delete
      env:
        AWS_ACCESS_KEY_ID: ${{ secrets.DESIGN_DEPLOYER_AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.DESIGN_DEPLOYER_AWS_SECRET_ACCESS_KEY }}
        AWS_REGION: 'eu-west-2'
      if: steps.clouddeploy.outcome == 'success'
    - name: Invalidate CloudFront
      uses: awact/cloudfront-action@master
      env:
        SOURCE_PATH: '/*'
        AWS_REGION: 'eu-west-2'
        AWS_ACCESS_KEY_ID: ${{ secrets.DESIGN_DEPLOYER_AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.DESIGN_DEPLOYER_AWS_SECRET_ACCESS_KEY }}
        DISTRIBUTION_ID: ${{ secrets.VAPOR_DESIGN_DISTRIBUTION_ID }}
